var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var WebSocket = require('ws');

var liujiangxinRouter = require('./routes/liujiangxin');
var ybyRouter = require('./routes/yanbingyi');
var wzbRouter = require('./routes/wangzibo');
var zywRouter = require('./routes/zhangyongwei');
var wddRouter = require('./routes/wangxiangdong');

var app = express();

// 基础中间件配置
app.use(cors({
  origin: 'http://localhost:3000',
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
  exposedHeaders: ['Content-Range', 'X-Content-Range']
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// 静态文件服务
app.use('/public', express.static(path.join(__dirname, 'public')));

// 路由挂载
app.use('/liujiangxin', liujiangxinRouter);
app.use('/yby', ybyRouter);
app.use('/wzb', wzbRouter);
app.use('/zyw', zywRouter);
app.use('/wxd', wddRouter);

// 404 错误处理
app.use(function(req, res, next) {
  next(createError(404));
});

// 错误处理中间件
app.use(function(err, req, res, next) {
  // 设置本地变量，仅在开发环境提供错误信息
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // 发送错误响应
  res.status(err.status || 500);
  res.json({
    status: 'error',
    message: err.message || '服务器内部错误'
  });
});

// 添加错误处理中间件
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(err.status || 500).json({
    status: 1,
    message: err.message || '服务器内部错误'
  });
});

// 添加未捕获的Promise rejection处理
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

// 添加未捕获的异常处理
process.on('uncaughtException', (err) => {
  console.error('Uncaught Exception:', err);
});

// 创建 WebSocket 服务器
const wsServer = new WebSocket.Server({ noServer: true });

// WebSocket 连接处理
wsServer.on('connection', function connection(ws) {
  console.log('WebSocket client connected');
  
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.on('error', function(error) {
    console.error('WebSocket error:', error);
  });
});

// 导出 WebSocket 服务器以便在 bin/www 中使用
app.wsServer = wsServer;

module.exports = app;
